package com.minelx.serverandclient.connector;

import com.minelx.serverandclient.stream.divider.Generator;
import com.minelx.serverandclient.stream.data.StreamCache;
import com.minelx.serverandclient.stream.data.Packet;

import java.io.IOException;
import java.io.OutputStream;

public class PacketWriter {

	private static final byte[] END_SEGMENT = new byte[0];

	private final OutputStream out;

	private final StreamCache.Renderer cacheRenderer;

	public PacketWriter(OutputStream out) {
		this.out = out;
		cacheRenderer = StreamCache.Renderer.singleton();
	}

	public void writePacket(Packet packet) throws IOException {
		Generator<StreamCache> cacheGenerator = packet.serialize();
		while (cacheGenerator.hasNext()) {
			out.write(cacheGenerator.next().getCacheBytes());
		}
		writeEndSegment();
	}

	private void writeEndSegment() {
		try {
			StreamCache rendered = cacheRenderer.render(END_SEGMENT);
			out.write(rendered.getCacheBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
